#include "ChessBoardView.h"

ChessBoardView::ChessBoardView(QWidget *parent) : QWidget(parent)
{
    init();
}

void ChessBoardView::init()
{
    setGeometry(0, 22, 664, 685);
    setMouseTracking(true);
    setAutoFillBackground(true);
    show();
}

void ChessBoardView::draw(Field * object)
{
    objects.append(object);
}

void ChessBoardView::setPossibleMoves(const PossibleMoves &moves)
{
    possibleMoves = moves;

    repaint();
}

void ChessBoardView::clearDrawable()
{
    objects.clear();
}

void ChessBoardView::markMouseOverField(QPainter &painter)
{
    QPen pen;
    pen.setColor(QColor("white"));
    painter.setPen(pen);

    int tmp[2];
    Position::coords2index(mouseY, mouseX, tmp);

    painter.drawRect(24 + 77 * tmp[1], 24 + 77 * tmp[0], 76, 76);
}

void ChessBoardView::markPossibleMoves(QPainter &painter)
{
    //na zielono tam gdzie moze sie ruszyć
    foreach(QVector<int> index, possibleMoves.onFreeFields) {
        painter.setPen(QColor("lime"));
        painter.drawRect(24 + 77 * index[1], 24 + 77 * index[0], 76, 76);
    }

    //na czerwono tam gdzie bicie
    foreach(QVector<int> index, possibleMoves.onNonFreeFields) {
        painter.setPen(QColor("red"));
        painter.drawRect(24 + 77 * index[1], 24 + 77 * index[0], 76, 76);
    }
}

void ChessBoardView::paintEvent(QPaintEvent *)
{
    QPalette palette;

    palette.setBrush(backgroundRole(), QBrush(QPixmap("./images/board.png")));
    setPalette(palette);

    QPainter painter(this);

    foreach(Field * object, objects) {
        if(object->getFigure() != nullptr) {
            QPixmap pixmap;
            pixmap.load(object->getFigure()->getImage());

            int index[2];
            Position::position2index(object->getPosition(), index);
            painter.drawPixmap(24 + 77 * index[1], 24 + 77 * index[0], pixmap.width(), pixmap.height(), pixmap);
        }
    }

    //obwódka tego nad którym jest wskaźnik myszki
    markMouseOverField(painter);

    //obwódki dla możliwych ruchów
    markPossibleMoves(painter);
}

void ChessBoardView::mouseMoveEvent(QMouseEvent * e)
{
    int indexC[2], indexE[2];
    Position::coords2index(mouseY, mouseX, indexC);
    Position::coords2index(e->y(), e->x(), indexE);

    if(indexC[0] != indexE[0] || indexC[1] != indexE[1]) {
        mouseX = e->x(); mouseY = e->y();

        if(Position::isOverChessBoard(mouseY, mouseX))
             emit mouseMoved(mouseX, mouseY);

    }
    //repaint
}

ChessBoardView::~ChessBoardView() {
}
